-
Notifications
You must be signed in to change notification settings - Fork 2.3k
feat: Add CORS configuration for browser-based MCP clients #1059
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
|
||
| # Add CORS middleware to expose Mcp-Session-Id header for browser-based clients | ||
| starlette_app.add_middleware( | ||
| CORSMiddleware, | ||
| allow_origins=["*"], # Allow all origins - adjust as needed for production | ||
| allow_methods=["GET", "POST", "DELETE"], # MCP streamable HTTP methods | ||
| expose_headers=["Mcp-Session-Id"], | ||
| ) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You need to wrap the whole application instead of using add_middleware, otherwise 500s don't get in this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you!
- Add CORSMiddleware to streamable HTTP example servers - Configure minimal CORS with Mcp-Session-Id exposed - Add CORS documentation section to README This enables browser-based clients to connect to MCP servers by properly exposing the Mcp-Session-Id header required for session management. Reported-by: Jerome
7a554e7 to
28aaa02
Compare
Co-authored-by: Marcelo Trylesinski <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Requesting changes to put back in your queue for fixing CI
That's a flaky test. |
|
We still need to address comment in #1059 (comment) for examples, only readme was changed, right? |
Summary
Mcp-Session-IdheaderProblem
Browser-based MCP clients cannot access the
Mcp-Session-Idheader from initialization responses due to CORS restrictions. Without this header, they cannot establish sessions with MCP servers.Solution
This PR adds Starlette's
CORSMiddlewareto the example servers and configures it to expose theMcp-Session-Idheader viaexpose_headers. The configuration is minimal, only allowing the HTTP methods required by the MCP protocol (GET, POST, DELETE).Changes
CORSMiddlewareimport and configuration to:examples/servers/simple-streamablehttp/mcp_simple_streamablehttp/server.pyexamples/servers/simple-streamablehttp-stateless/mcp_simple_streamablehttp_stateless/server.pyTest plan
Mcp-Session-Idheader from responsesReported-by: Jerome